package com.web.controller;

import com.alibaba.fastjson.JSON;
import com.web.entity.ResponseResult;
import com.web.entity.User;
import com.web.service.UserService;
import com.web.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/login")
public class UserLoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            req.setCharacterEncoding("UTF-8");
            resp.setCharacterEncoding("UTF-8");
            resp.setContentType("text/html;charset=UTF-8");

            String username = req.getParameter("username");
            String password = req.getParameter("password");

            UserService userService = new UserServiceImpl();
            User user = userService.login(username, password);

            if (user != null) {
                String str = JSON.toJSONString(new ResponseResult(200, user, "登录成功"));
                resp.getWriter().write(str);
            } else {
                String str = JSON.toJSONString(new ResponseResult(401, null, "用户名或密码错误"));
                resp.getWriter().write(str);
            }
        } catch (Exception e) {
            e.printStackTrace();
            String str = JSON.toJSONString(new ResponseResult(500, null, "服务器内部错误: " + e.getMessage()));
            resp.getWriter().write(str);
        }
    }
}